import { App } from "../App";

const { menu, ccclass, property } = cc._decorator;
@ccclass
@menu("自定义插件/通用弹出对话框")
export default class MessageBox extends cc.Component {
    @property({ type: cc.Label, tooltip: '弹框标题' })
    lblTitle: cc.Label = null;
    @property({ type: cc.RichText, tooltip: '弹框消息文本' })
    lblMBtext: cc.RichText = null;
    @property({ type: cc.Label, tooltip: '确认按钮文本' })
    lblOK: cc.Label = null;
    @property({ type: cc.Label, tooltip: '取消按钮文本' })
    lblCancel: cc.Label = null;

    private _msgBtnText: string[] = [];
    private _callBack:(id:number)=>void;
    private _canvasSize = cc.size(0,0);

    onLoad () {
        this._callBack = null;
        this._msgBtnText[0] = this.lblOK.string;
        this._msgBtnText[1] = this.lblCancel.string;
        this._canvasSize = cc.view.getFrameSize();
    }

    onClick(_: any, userData: any) {
        cc.tween(this.node)
        .to(0.2,{opacity:0},{easing:'quadIn'})
        .call(()=>{
            this._callBack && this._callBack(parseInt(userData));
            this._callBack = null;
            this.node.scale = 0;
            cc.tween(this).stop();
        }).start();
    }

    public showMessage(text: string, call?: (flag: number) => void){
        let txts = text.split('|');
        if (txts.length < 3) return ;

        if (this.node.width !== this._canvasSize.width || this.node.height !== this._canvasSize.height){
            App.justNode(this.node);
        }
        
        this.lblTitle.string = txts[0];
        this.lblMBtext.string = txts[1];
        this.node.opacity = 0;
        this.node.scale = 1;
        this.node.active = true;

        // 设置按钮显示文本
        if (txts.length === 4) {
            this.lblOK.string = txts[2];
            this.lblCancel.string = txts[3];
            this.lblOK.node.parent.x = -150;
            this.lblCancel.node.parent.x = 150;
            this.lblOK.node.parent.active = true;
            this.lblCancel.node.parent.active = true;
        } else if (txts.length === 3){
            this.lblOK.string = txts[2];
            this.lblOK.node.parent.x = 0;
            this.lblOK.node.parent.active = true;
            this.lblCancel.node.parent.active = false;
        }
        cc.tween(this.node).to(0.2,{opacity:255},{easing:'quadIn'}).start();
        this._callBack = call;
    }
}
